package com.miaoxie.web.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author @author miaoxie
 * @date 2022/2/16 4:46 下午
 */
@RestController
public class PortController {
    @Value(value = "${server.port}")
    String port;


    @GetMapping("/getPort")
    public String getPort(){
        return getIp() + ":" + port;
    }

    private String getIp() {
        List<String> iplist = new ArrayList<String>();
        try {
            String a = "";

            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                Enumeration<InetAddress> obj = ni.getInetAddresses();
                while (obj.hasMoreElements()) {

                    InetAddress ia = obj.nextElement();
                    iplist.add(ia.getHostAddress());
                }
                ip = (InetAddress) ni.getInetAddresses().nextElement();

                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {
                    a = ip.getHostAddress();
                    break;
                } else {
                    ip = null;
                }
            }
        } catch (Exception ex) {

        }

        String aaa = "";
        for (String a : iplist) {
            aaa += "******" + a + "***";
        }
        return aaa;
    }
}
